from __future__ import absolute_import
import logging

from os.path import join

from forest.api import Command, get_tool

import re

logger = logging.getLogger('forest.commands.ZeroMBR')

pat = re.compile('([hs]d\w)$', re.M)

class ZeroMBR(Command):
    ''' deletes the master boot table on all disks,
        except the ones specified to skip

        only the ignore list is read from the config.
        no install_root or equivalent param - simply 'destroys'
        all disks on the machine it is run!

        if mbr type to create isn't specified
        , creates a 'normal' BIOS 'msdos' mbr
    '''
    __register__ = 'commands.install.ZeroMBR'

    requires_config = ['zerombr', 'install_mode']
    #dd if=/dev/zero of=/dev/sda bs=512 count=1
    def run(self, config):
        if not self.args:
            return

        skip = self.args.get('ignore', [])
        mbr_type = self.args.get('type', 'msdos')
        #get all drives

        installtree = config.get_install_root()
        get_tool('system.unmount')(join(installtree,'boot'), lazy=True)
        get_tool('system.unmount')(installtree, lazy=True)

        drives = self.args.get('drives')

        for disk_str in drives:
            if disk_str in skip:
                print 'Skipping disk %s' % disk_str
                continue

            print 'Clearing disk %s' % disk_str

            if mbr_type == 'gpt':
                get_tool('system.sgdisk')('/dev/{0}'.format(disk_str))
            elif mbr_type == 'msdos':
                get_tool('system.dd')('/dev/zero', '/dev/%s' % disk_str, 512, 1)

    @staticmethod
    def discover_drives():
        drives_file = open('/proc/partitions', 'r')
        drives_raw = drives_file.read()
        drives_file.close()

        disks = pat.finditer(drives_raw)
        drives = []
        for disk in disks:
            disk_str = disk.group(1).strip()
            if not disk_str:
                continue
            drives.append(disk_str)
        return drives
